package classes
{
	import classes.Music;
	import classes.MusicScanner;
	
	import flash.media.*;
	import flash.media.Sound;
	import flash.net.URLRequest;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.events.ListEvent;
	
	
	public class Player
	{
		private var channel:SoundChannel;
		private var selectedPathSong:String;
		private var index:int;
		
		public function Player()
		{
		}
		
		public function PlaySound(sound:String):void
		{
			try
			{
				// Make sure we don't get multiple songs playing at the same time
				StopSound();
				
				var mySong:Sound = new Sound();
				var req:URLRequest = new URLRequest(sound);
				mySong.load(req);
				// Play the song on the channel
				channel = mySong.play();
				
			}
			catch (e:Error)
			{
				Alert.show(e.toString());
			}
		}
		
		public function StopSound():void
		{
			
			// Stop the channel, but only if it exists
			if ( channel != null ) channel.stop();
		}
		
		//set the path of the file selected in the datagrid
		public function onItemClickhandler(e:ListEvent ):void
		{
			selectedPathSong = e.itemRenderer.data.pathLocationCol;		
			index = e.rowIndex;
		}
		
		public function getcurrentsong():String
		{
			return selectedPathSong;
		}
		
		public function playNext(files:ArrayCollection):void
		{
			var n:int = index + 1;
			if (n > files.length - 1)
				n = 0;
			var tmp:Music = files.getItemAt(n) as Music;
			index = n;
			selectedPathSong = tmp.pathLocationCol;
			PlaySound(tmp.pathLocationCol);
		}
		public function playPrev(files:ArrayCollection):void
		{
			var n:int = index - 1;
			if (n<0)
				n = files.length - 1;
			var tmp:Music = files.getItemAt(n) as Music;
			index = n;
			selectedPathSong = tmp.pathLocationCol;
			PlaySound(tmp.pathLocationCol);
		}
	}
}